//package com.ews.onlineexchange.service;
//
//import static java.util.Arrays.asList;
//
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.HashMap;
//import java.util.List;
//
//import javax.annotation.Resource;
//import javax.ejb.EJBException;
//import javax.ejb.SessionContext;
//import javax.ejb.Stateless;
//import javax.faces.context.ExternalContext;
//import javax.faces.context.FacesContext;
//import javax.inject.Inject;
//import javax.inject.Named;
//import javax.persistence.EntityManager;
//import javax.ws.rs.client.Client;
//import javax.ws.rs.client.ClientBuilder;
//import javax.ws.rs.client.Entity;
//import javax.ws.rs.client.Invocation.Builder;
//import javax.ws.rs.core.Context;
//import javax.ws.rs.core.Form;
//import javax.ws.rs.core.MediaType;
//import javax.ws.rs.core.Response;
//import javax.ws.rs.core.SecurityContext;
//
//import org.apache.commons.lang3.StringUtils;
//import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
//import org.keycloak.admin.client.Keycloak;
//import org.keycloak.admin.client.KeycloakBuilder;
//import org.keycloak.admin.client.resource.RoleMappingResource;
//import org.keycloak.admin.client.resource.RoleScopeResource;
//import org.keycloak.admin.client.resource.UserResource;
//import org.keycloak.admin.client.resource.UsersResource;
//import org.keycloak.representations.idm.CredentialRepresentation;
//import org.keycloak.representations.idm.RoleRepresentation;
//import org.keycloak.representations.idm.UserRepresentation;
//
//import com.ews.onlineexchange.exception.InvalidUsernameAndPasswordException;
//import com.ews.onlineexchange.exception.KeycloakException;
//import com.ews.onlineexchange.model.ServiceBuyer;
//import com.ews.onlineexchange.model.ServiceSupplier;
//import com.ews.onlineexchange.model.User;
//import com.ews.onlineexchange.util.Config;
//
//@Stateless
//@Named
//public class KeycloakUserService {
//	private static final String APP_REALM = "onlineExchangeRealm";
//	private static final String ROOT_PASSWORD = "Winter is coming";
//	private static final String ROOT_USERNAME = "wcq";
//	private static final String MASTER_REALM = "master";
//	private static final String KEYCLOAK_SERVER_URL = "http://%s:%s/auth";
//
//	public static final String ROLE_PROFESSION = "profession";
//	public static final String ROLE_ADMIN = "admin";
//
//	public static final String[] ADMIN_ROLES = {"admin", "credentialManager", "businessManager","reporter", "auditor", "worker", "director", "secretary"};
//
//	@Inject
//	EntityManager entityManager;
//
//	@Resource
//	SessionContext sessionContext;
//
//	@Inject
//	Config config;
//
//	private Keycloak initKeycloakClientAdapter() {
//		return KeycloakBuilder.builder()
//				.serverUrl(getKeyCloakServerUrl())
//				.realm(MASTER_REALM)
//				.username(ROOT_USERNAME)
//				.password(ROOT_PASSWORD)
//				.clientId("admin-cli")
//				.resteasyClient(
//						new ResteasyClientBuilder().connectionPoolSize(10).build()
//				).build();
//	}
//
//	private String getKeyCloakServerUrl() {
//		String serverPort = System.getProperty("serverPort");
//		String serverIp = System.getProperty("serverIp");
//		String keycloakServerUrl = String.format(KEYCLOAK_SERVER_URL, serverIp, serverPort);
//		return keycloakServerUrl;
//	}
//
//	/**
//	 * 用户添加
//	 * @throws KeycloakException
//	 */
//	public String persistServiceSupplier(ServiceSupplier serviceSupplier)  {
//		Keycloak kc = initKeycloakClientAdapter();
//
//		CredentialRepresentation credential = new CredentialRepresentation();
//		credential.setType(CredentialRepresentation.PASSWORD);
//		credential.setValue(serviceSupplier.getPassword());
//		credential.setTemporary(false);
//		UserRepresentation user = new UserRepresentation();
//		user.setUsername(serviceSupplier.getUsername());
//		user.setEnabled(true);
//		user.setEmail(serviceSupplier.getEmail());
//		HashMap<String, List<String>> userAttributes = new HashMap<String, List<String>>();
//		userAttributes.put("fullname", Arrays.asList(serviceSupplier.getCnname()));
//		user.setAttributes(userAttributes);
//		user.setCredentials(Arrays.asList(credential));
//
//		Response result = kc.realm(APP_REALM).users().create(user);
//
//		if (result.getStatus() != 201) {
//			System.err.println("Couldn't create user.");
//			throw new KeycloakException();
//		}
//
//		String locationHeader = result.getHeaderString("Location");
//		String userId = locationHeader.replaceAll(".*/(.*)$", "$1");
//
//		RoleRepresentation savedRoleRepresentation = kc.realm(APP_REALM).roles()
//				.get("supplier").toRepresentation();
//		kc.realm(APP_REALM).users().get(userId).roles().realmLevel()
//				.add(asList(savedRoleRepresentation));
//
//		return "ok";
//	}
//
//	public String persistServiceBuyer(ServiceBuyer serviceBuyer) {
//		Keycloak kc = initKeycloakClientAdapter();
//
//		CredentialRepresentation credential = new CredentialRepresentation();
//		credential.setType(CredentialRepresentation.PASSWORD);
//		credential.setValue(serviceBuyer.getPassword());
//		credential.setTemporary(false);
//
//		UserRepresentation user = new UserRepresentation();
//		user.setUsername(serviceBuyer.getUsername());
//		user.setEnabled(false);
//		user.setEmail(serviceBuyer.getEmail());
//		HashMap<String, List<String>> userAttributes = new HashMap<String, List<String>>();
//		userAttributes.put("fullname", Arrays.asList(serviceBuyer.getCnname()));
//		user.setAttributes(userAttributes);
//		user.setCredentials(Arrays.asList(credential));
//
//		Response result = kc.realm(APP_REALM).users().create(user);
//
//		if (result.getStatus() != 201) {
//			System.err.println("Couldn't create user.");
//			throw new KeycloakException();
//		}
//
//		String locationHeader = result.getHeaderString("Location");
//		String userId = locationHeader.replaceAll(".*/(.*)$", "$1");
//
//		RoleRepresentation savedRoleRepresentation = kc.realm(APP_REALM).roles()
//				.get("buyer").toRepresentation();
//		kc.realm(APP_REALM).users().get(userId).roles().realmLevel()
//				.add(asList(savedRoleRepresentation));
//
//		return "ok";
//	}
//
//	public String persistUser(User systemUser, List<String> roleList) {
//		Keycloak kc = initKeycloakClientAdapter();
//
//		CredentialRepresentation credential = new CredentialRepresentation();
//		credential.setType(CredentialRepresentation.PASSWORD);
//		credential.setValue(systemUser.getPassword());
//		credential.setTemporary(false);
//
//		UserRepresentation user = new UserRepresentation();
//		user.setUsername(systemUser.getUsername());
//		user.setEnabled(false);
//		user.setEmail(systemUser.getEmail());
//		HashMap<String, List<String>> userAttributes = new HashMap<String, List<String>>();
//		userAttributes.put("fullname", Arrays.asList(systemUser.getCnname()));
//		user.setAttributes(userAttributes);
//		user.setCredentials(Arrays.asList(credential));
//
//		Response result = kc.realm(APP_REALM).users().create(user);
//
//		if (result.getStatus() != 201) {
//			System.err.println("Couldn't create user.");
//			throw new EJBException();
//		}
//
//		String locationHeader = result.getHeaderString("Location");
//		String userId = locationHeader.replaceAll(".*/(.*)$", "$1");
//		RoleScopeResource realmLevel = kc.realm(APP_REALM).users().get(userId).roles().realmLevel();
//
//		for (String rolename : roleList) {
//			RoleRepresentation savedRoleRepresentation = kc.realm(APP_REALM).roles()
//					.get(rolename).toRepresentation();
//			realmLevel.add(asList(savedRoleRepresentation));
//		}
//
//		for (String rolename : ADMIN_ROLES) {
//			if (roleList.contains(rolename))
//				continue;
//			RoleRepresentation savedRoleRepresentation = kc.realm(APP_REALM).roles()
//					.get(rolename).toRepresentation();
//			realmLevel.remove(asList(savedRoleRepresentation));
//		}
//
//		return "ok";
//	}
//
//	public String updateRoles(User instance, List<String> roleList) {
//		Keycloak kc = initKeycloakClientAdapter();
//		RoleScopeResource realmLevel = kc.realm(APP_REALM).users().get(findUserRepresentation(instance.getUsername()).getId()).roles().realmLevel();
//
//		for (String rolename : roleList) {
//			RoleRepresentation savedRoleRepresentation = kc.realm(APP_REALM).roles()
//					.get(rolename).toRepresentation();
//			realmLevel.add(asList(savedRoleRepresentation));
//		}
//
//		for (String rolename : ADMIN_ROLES) {
//			if (roleList.contains(rolename))
//				continue;
//			RoleRepresentation savedRoleRepresentation = kc.realm(APP_REALM).roles()
//					.get(rolename).toRepresentation();
//			realmLevel.remove(asList(savedRoleRepresentation));
//		}
//
//		return "ok";
//	}
//
//
//
//	/**
//	 * 用户禁用
//	 */
//	public void disableUser(User systemUser) {
//		Keycloak kc = initKeycloakClientAdapter();
//
//		UsersResource userResource = kc.realm(APP_REALM).users();
//		List<UserRepresentation> resultList = userResource.search(systemUser.getUsername());
//		for (UserRepresentation user : resultList) {
//			user.setEnabled(false);
//			userResource.get(user.getId()).update(user);
//		}
//	}
//
//	/**
//	 * 用户删除
//	 */
//	public void deleteUser(User systemUser) {
//		Keycloak kc = initKeycloakClientAdapter();
//		UsersResource userResource = kc.realm(APP_REALM).users();
//		List<UserRepresentation> resultList = userResource.search(systemUser.getUsername());
//		for (UserRepresentation user : resultList) {
//			userResource.get(user.getId()).remove();
//		}
//	}
//	/**
//	 * 修改用户邮箱
//	 */
//	public void updateEmail(User systemUser) {
//		Keycloak kc = initKeycloakClientAdapter();
//
//		UsersResource userResource = kc.realm(APP_REALM).users();
//		List<UserRepresentation> resultList = userResource.search(systemUser.getUsername());
//		for (UserRepresentation user : resultList) {
//			user.setEmail(systemUser.getEmail());
//			userResource.get(user.getId()).update(user);
//		}
//	}
//
//	/**
//	 * 用户启用
//	 */
//	public void enableUser(User systemUser) {
//		Keycloak kc = initKeycloakClientAdapter();
//
//		UsersResource userResource = kc.realm(APP_REALM).users();
//		List<UserRepresentation> resultList = userResource.search(systemUser.getUsername());
//		for (UserRepresentation user : resultList) {
//			user.setEnabled(true);
//			userResource.get(user.getId()).update(user);
//		}
//	}
//
//	/**
//	 * 修改密码
//	 * @throws InvalidUsernameAndPasswordException
//	 */
//	public void changePassword(User systemUser, String oldPassword, String password) throws InvalidUsernameAndPasswordException {
//
//		boolean isValid = getAccessToken(systemUser.getUsername(), oldPassword);
//		if (!isValid) {
//			throw new InvalidUsernameAndPasswordException();
//		}
//		Keycloak kc = initKeycloakClientAdapter();
//
//		CredentialRepresentation credential = new CredentialRepresentation();
//		credential.setType(CredentialRepresentation.PASSWORD);
//		credential.setValue(password);
//		credential.setTemporary(false);
//
//		UsersResource userResource = kc.realm(APP_REALM).users();
//		List<UserRepresentation> resultList = kc.realm(APP_REALM).users().search(systemUser.getUsername());
//		for (UserRepresentation user : resultList) {
//			userResource.get(user.getId()).resetPassword(credential);
//		}
//	}
//
//	/**
//	 * 重置密码
//	 * @throws InvalidUsernameAndPasswordException
//	 */
//	public void resetPassword(User systemUser,String password) throws InvalidUsernameAndPasswordException {
//		Keycloak kc = initKeycloakClientAdapter();
//		CredentialRepresentation credential = new CredentialRepresentation();
//		credential.setType(CredentialRepresentation.PASSWORD);
//		credential.setValue(password);
//		credential.setTemporary(false);
//
//		UsersResource userResource = kc.realm(APP_REALM).users();
//		List<UserRepresentation> resultList = kc.realm(APP_REALM).users().search(systemUser.getUsername());
//		for (UserRepresentation user : resultList) {
//			userResource.get(user.getId()).resetPassword(credential);
//		}
//	}
//
//	public boolean getAccessToken(String username, String oldPassword) {
//		Client client = ClientBuilder.newClient();
//		String url = getKeyCloakServerUrl().concat("/realms/").concat(APP_REALM).concat("/protocol/openid-connect/token");
//		Builder request = client.target(url).request("application/json");
//
//		request.header("content-type", "application/x-www-form-urlencoded");
//		request.header("accept", "application/json");
//		Form form = new Form();
//		form.param("grant_type", "password");
//		form.param("username", username);
//		form.param("password", oldPassword);
//		form.param("client_id", "admin-cli");
//		Response response = request.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
//		int status = response.getStatus();
//		client.close();
//		return status == 200;
//	}
//
//	/**
//	 * 查询用户名是否被占用
//	 */
//	public boolean isUsernameExist(String username) {
//		if (StringUtils.isBlank(username))
//			return false;
//		Keycloak kc = initKeycloakClientAdapter();
//		List<UserRepresentation> resultList = kc.realm(APP_REALM).users().search(username);
//		return resultList.size() > 0;
//	}
//
//	/**
//	 *  根据用户名查询用户
//	 */
//	public UserRepresentation findUserRepresentation (String username ) {
//		if (StringUtils.isBlank(username))
//			return null;
//		Keycloak kc = initKeycloakClientAdapter();
//		List<UserRepresentation> resultList = kc.realm(APP_REALM).users().search(username);
//		if (resultList.size() > 0)
//			return resultList.get(0);
//		return null;
//	}
//
//	/**
//	 * 查询邮箱是否被占用
//	 */
//	public boolean isEmailAddressExist(String email) {
//		if (StringUtils.isBlank(email))
//			return false;
//		Keycloak kc = initKeycloakClientAdapter();
//		List<UserRepresentation> resultList = kc.realm(APP_REALM).users().search(null, null, null, email, 0, 10);
//		return resultList.size() > 0;
//	}
//
//	/**
//	 * 根据keycloak用户ID搜索用户名称
//	 */
//	public String findUsername(String id) {
//		try {
//			Keycloak kc = initKeycloakClientAdapter();
//			UserResource userResource = kc.realm(APP_REALM).users().get(id);
//			UserRepresentation representation = userResource.toRepresentation();
//			return representation.getUsername();
//		} catch (Exception e) {
//			if(e.getMessage().indexOf("RESTEASY004645: templateValues entry was null") != -1) {
//				ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
//				try {
//					//跳转的到首页
//					externalContext.redirect(externalContext.getApplicationContextPath());
//				} catch (IOException e1) {
//					e1.printStackTrace();
//				}
//			}
//		}
//		return null;
//	}
//
//	@Context
//	SecurityContext securityContext;
//
//	public String findLoginedUsername() {
////		FacesContext currentInstance = FacesContext.getCurrentInstance();
////		if (currentInstance == null)
////			return null;
////		ExternalContext externalContext = currentInstance.getExternalContext();
//		String remoteUser = sessionContext.getCallerPrincipal().getName();
//
//		if (!StringUtils.isBlank( remoteUser ))
//			remoteUser = findUsername(remoteUser);
//		else
//			return null;
//		return remoteUser;
//	}
//
//	/**
//	 * 查询用户角色
//	 */
//	public List<String> queryRolesOfUser(String username) {
//		Keycloak kc = initKeycloakClientAdapter();
//		UserRepresentation userRepresentation = findUserRepresentation(username);
//		UserResource userResource = kc.realm(APP_REALM).users().get(userRepresentation.getId());
//		RoleMappingResource roles = userResource.roles();
//		List<RoleRepresentation> listAll = roles.realmLevel().listAll();
//		List<String> resultList = new ArrayList<>();
//		List<String> availableRoles = Arrays.asList(ADMIN_ROLES);
//		for (RoleRepresentation roleRepresentation : listAll) {
//			String rolename = roleRepresentation.getName();
//			if (availableRoles.contains(rolename)) {
//				resultList.add(rolename);
//			}
//		}
//		return resultList;
//	}
//
//	public boolean isUserInRole( String rolename ) {
//		return sessionContext.isCallerInRole( rolename );
//	}
//}
